package com.sptpc.book.controller;

import com.sptpc.book.controller.request.NewBookRequest;
import com.sptpc.book.model.Book;
import com.sptpc.book.service.BookService;
import com.sptpc.book.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BookService bookService;

    @GetMapping("/")
    public ModelAndView getBooks(@RequestParam("category") Long categoryId){
        ModelAndView mv=new ModelAndView("user/books");
        List<Book> books=bookService.getAllBooks(categoryId);
        mv.addObject("book",books);
        return mv;
    }

    @PostMapping("/save")
    public Book creatNewBook(NewBookRequest bookRequest) {
        if (bookRequest.getCategoryId() != null) {
            return bookService.saveBook(bookRequest);
        }
        return null;
    }

}
